package raptor;

import javax.swing.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;

public class UDPClient extends SendRecieve {
    JFrame frame;
    JPanel panel;
    JTextField field1, field2, field3;
    JTextArea area;
    JScrollPane pane;
    JLabel label;
    JButton button;

    public static void main(String[] args) {
        UDPClient u = new UDPClient();
    }

    public UDPClient(){
        frame = new JFrame("Text Client");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setUndecorated(true);
        frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
        panel = new JPanel();
        panel.setLayout(null);

        label = new JLabel("Desination IP:");
        label.setBounds(10, 20, 100, 30);
        panel.add(label);

        field1 = new JTextField(20);
        field1.setText("localhost");
        field1.setBounds(125, 25, 150, 20);
        panel.add(field1);

        label = new JLabel("Destination Port:");
        label.setBounds(10, 50, 100, 30);
        panel.add(label);

        field2 = new JTextField(10);
        Integer sendClientPort = PORT+1;
        field2.setText(sendClientPort.toString());
        field2.setBounds(125, 55, 100, 20);
        panel.add(field2);

        field3 = new JTextField(50);
        field3.setBounds(10, 310, 200, 30);
        panel.add(field3);

        area = new JTextArea();
        pane = new JScrollPane(area);
        pane.setBounds(10, 100, 300, 200);
        panel.add(pane);
        
        button = new JButton("Send");
        button.setBounds(235, 310, 75, 30);

        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                new SendRequest();
            }
        });

        panel.add(button);
        frame.add(panel);
        frame.setSize(400, 400);
        frame.setVisible(true);

        listen(false);
    }

    public class SendRequest{
        public SendRequest() {
            try {
                InetAddress address;
                String dip = field1.getText();
                address = InetAddress.getByName(dip);
                String port = field2.getText();
                int pnum = Integer.parseInt(port);
                String mess = field3.getText();
                byte message[] = mess.getBytes();
                send(message, address, pnum);
                field3.setText("");
            } catch(IOException io){}
        }
    }

    public void output(byte[] buf, InetAddress client) {
        area.append("Received: " + new String(buf).trim() +" [" + client + "]:");
        area.append("\n");
    }
}
